package com.lz.yz.member.web;

import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.Constant;
import com.lz.yz.member.model.AttentionsModel;
import com.lz.yz.member.param.AttentionsParam;
import com.lz.yz.member.service.AttentionsService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
* Created by CodeGenerator on 2017/11/09.
*/
@RestController
@RequestMapping("/attentions")
public class AttentionsController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HttpServletRequest request;

    @Autowired
    AttentionsService attentionsService;

    @ApiOperation(value="添加关注或取消关注")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "model", value = "关注实体", dataType = "AttentionsModel", paramType = "body"),
            @ApiImplicitParam(paramType = "header",name = "Authorization",value = "Bearer token")
    })
    @PostMapping
    public ReturnValue insertAttention(@RequestBody AttentionsModel model) throws Exception {
        try {
            Integer accountId = (Integer) request.getAttribute("accountId");
            model.setAccountId(accountId);
            return attentionsService.insert(model);
        } catch (Exception e) {
            logger.error("添加关注或取消关注失败", e);
            return ReturnValue.generateFalseReturnValue("添加关注或取消关注失败!");
        }
    }

    @ApiOperation(value="关注列表分页",response = AttentionsModel.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "Authorization",value = "Bearer token"),
            @ApiImplicitParam(paramType = "query",name = "page", value = "当前页"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "每页条数"),
            @ApiImplicitParam(paramType = "query",name = "targetId", value = "关注目标ID"),
    })
    @GetMapping
    public ReturnValue listAttentions(Integer targetId, @RequestParam Optional<Integer> pageSize, @RequestParam Optional<Integer> page) {
        try {
            Integer accountId = (Integer) request.getAttribute("accountId");
            AttentionsParam param=new AttentionsParam(pageSize.orElse(Constant.DEFAULT_PAGE_SIZE),page.orElse(1));
            param.setLoginId(accountId);
            if(targetId == null){
                param.setAccountId(accountId);
            }else {
                param.setTargetId(targetId);
            }
            return attentionsService.listAttentions(param);
        } catch (Exception e) {
            logger.error("关注列表分页失败", e);
            return ReturnValue.generateFalseReturnValue("关注列表分页失败!");
        }
    }
}
